<?php
/**
 * EcgaTable控制器
 *
 * PHP version 5
 *
 * @package   Ecga
 * @author    v.k <none@none.com>
 * @copyright 2010 Xingchangxinda Inc.
 * @version   SVN: $Id$
 */
namespace Project\Apps\Ecga\Controllers;

use \Project\Apps\Ecga\Controllers\Abstraction\EcgaController;
use \Framework\System\Helper\HttpResponse;

use \Project\Apps\Ecga\Models\Table\EcgaTable;
use \Project\Apps\Ecga\Models\Table\TableOutputer;


/**
 * EcgaTable控制器
 *
 * PHP version 5
 *
 * @package   Ecga
 * @author    v.k <none@none.com>
 * @copyright 2010 Xingchangxinda Inc.
 * @version   Release: <0.1>
 **/
class Table extends EcgaController
{
    /**
     * 显示数据表
     *
     * @param HttpRequest $request Http请求
     *
     * @return void
     */
    public static function show($request)
    {
        $table = self::getRequestTable($request);
        $tableName = $request->get('table', 'string');
        
        if (null === $table) {
            HttpResponse::notFound();
            return ;
        }
        
        $sortField = $request->get('sortfield', 'string');
        $sortMethod = strtolower($request->get('sortmethod', 'string'));
        $sortField != '' && $table->sortField = $sortField;
        $sortMethod != '' && $table->sortMethod = $sortMethod;
        $table->setRowFormater('html', $tableName)->generate();
        $page = self::createPage();
        
        $page->setTitle($table->name)
            ->assign('table', $table)
            ->assign('maxDate', date('Y-m-d', strtotime('-1 day')));
        HttpResponse::output($page->render('table'));
    }
    
    /**
     * 导出数据表
     *
     * @param HttpRequest $request Http请求
     *
     * @return void
     */
    public static function export($request)
    {
        $table = self::getRequestTable($request);
        $tableName = $request->get('table', 'string');

        if (null === $table) {
            HttpResponse::notFound();
            return ;
        }

        $table->setRowFormater('excel', $tableName)->generate();

        $outputer = TableOutputer::create(TableOutputer::EXCEL, $table);

        $outputer->output();
    }

    /**
     * 获取请求的数据表
     *
     * @param HttpRequest $request Http请求
     *
     * @return EcgaTable
     */
    protected static function getRequestTable($request)
    {
        $tableName = $request->get('table', 'string');
        $table = EcgaTable::create($tableName);
        
        if (null === $table) {
            return null;
        }

        foreach ($table->getFilters() as $filter) {
            $table->setFilterValue(
                $filter->name,
                urldecode($request->get($filter->name, 'string', 0))
            );
        }

        return $table;
    }
}
